

import { Skill } from "../class/skill";
import { GameBalance } from "../data/GameBalance";
import DD from "../manager/dynamic_data_manager";
import JsonManager from "../manager/json_manager";
import MainManager from "../manager/main_manager";
import PoolManager from "../manager/pool_manager";
import StorageManager from "../manager/storage_manager";
import { Emitter } from "../utils/emmiter";
import { MessageType } from "../utils/message";
import { Utils } from "../utils/utils";
import Ball from "./Ball";
import Bullet from "./Bullet";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Player extends cc.Component {

    interval: number = 0.5;
    fireInterval: number = 3;
    canSpred: boolean = false;
    bulletSpeed: number = 50000;

    // bulletCount:number=1;
    onLoad() {
        Emitter.register(MessageType.addSkill, (name, data) => {
            this.applySkillEffect()
        }, '')
        this.schedule(this.fireBullets, this.fireInterval);
    }

    takeDAmge(value: number) {
        StorageManager.instance.playerData.hp -= value;
        if (StorageManager.instance.playerData.hp <= 0) {
            if (!MainManager.instance.isEndGame) {
                MainManager.instance.isEndGame = true
                Emitter.fire(MessageType.gameFail)
            }

        }
    }

    fireBullets() {
        let nearestEnemy = this.findNearestEnemy();
        if (!nearestEnemy) {
            console.warn("No target specified for shooting!");
            return;
        }
        let count = StorageManager.instance.playerData.bulletCount;

        // 计算指向目标的方向

        // 确保计算方向时只考虑 2D 平面上的 x 和 y 坐标
        const targetPosition = nearestEnemy.node.position;
        const directionToTarget = cc.v2(targetPosition.x - this.node.position.x, targetPosition.y - this.node.position.y).normalize();

        // 基准角度（以目标方向为基准）
        const baseAngle = Math.atan2(directionToTarget.y, directionToTarget.x) * (180 / Math.PI); // 转为角度
        const angleStep = 10; // 每颗子弹的偏移角度

        for (let i = 0; i < count; i++) {
            // 计算当前子弹的偏移角度
            let angleOffset = 0;
            if (i % 2 === 0) {
                // 偶数索引，从右侧增加
                angleOffset = Math.ceil(i / 2) * angleStep;
            } else {
                // 奇数索引，从左侧增加
                angleOffset = -Math.ceil(i / 2) * angleStep;
            }

            // 最终发射角度
            const finalAngle = baseAngle + angleOffset;
            const radian = finalAngle * (Math.PI / 180); // 角度转弧度
            let direction = cc.v2(Math.cos(radian), Math.sin(radian));

            // 生成子弹并设置初始位置
            let bullet = PoolManager.instance.createObjectByName('bullet', this.node.parent);
            // bullet.parent = this.node; // 将子弹添加到当前节点下
            bullet.setPosition(this.node.position)

            bullet.position = this.node.position; // 设置子弹初始位置
            let bulletScript = bullet.getComponent('Bullet');

            if (bulletScript) {
                bulletScript.init(nearestEnemy, StorageManager.instance.spreadCount); // 设置子弹的目标
            }
            // 给子弹施加力
            // const rigidBody = bullet.getComponent(cc.RigidBody);
            // if (rigidBody) {
            //     // rigidBody.applyForce(cc.v2(1,1))
            //     const force = direction.mul(this.bulletSpeed); // 根据方向和力大小计算力向量
            //     rigidBody.applyForce(force, rigidBody.getWorldCenter(), true); // 施加力
            //     // rigidBody.linearVelocity = direction.mul(this.bulletSpeed); // 设置线性速度
            //     // rigidBody.linearVelocity = direction.mul(this.bulletSpeed); // 设置线性速度
            // }
        }

        // let count = 0;

        // // 基准角度，正前方为 0 度
        // const baseAngle = 0;
        // // 每颗子弹之间的角度间隔（左右对称）
        // const angleStep = 15;

        // for (let i = 0; i < StorageManager.instance.playerData.bulletCount; i++) {
        //     // 计算当前子弹的角度
        //     let angleOffset = 0;
        //     if (count % 2 === 0) {
        //         // 偶数颗子弹，两侧对称
        //         angleOffset = (i - (count / 2 - 0.5)) * angleStep;
        //     } else {
        //         // 奇数颗子弹，中间为基准，两侧对称
        //         angleOffset = (i - Math.floor(count / 2)) * angleStep;
        //     }

        //     // 计算发射方向
        //     const radian = (baseAngle + angleOffset) * (Math.PI / 180); // 角度转弧度
        //     const direction = cc.v2(Math.cos(radian), Math.sin(radian));
        //     let nearestEnemy = this.findNearestEnemy();
        //     if (!nearestEnemy) return; // 没有敌人时不发射子弹

        //     // 创建子弹
        //     let bullet = PoolManager.instance.createObjectByName('bullet', this.node.parent);
        //     // bullet.parent = this.node; // 将子弹添加到当前节点下
        //     bullet.setPosition(this.node.position)

        //     // 初始化子弹目标
        //     let bulletScript = bullet.getComponent('Bullet');

        //     if (bulletScript) {
        //         bulletScript.init(nearestEnemy, StorageManager.instance.spreadCount); // 设置子弹的目标
        //     }


        //     // 给子弹施加力
        //     const rigidBody = bullet.getComponent(cc.RigidBody);
        //     if (rigidBody) {
        //         rigidBody.linearVelocity = direction.mul(this.bulletSpeed); // 设置线性速度
        //     }
        // }


    }

    fireBullet() {

        let nearestEnemy = this.findNearestEnemy();
        if (!nearestEnemy) return; // 没有敌人时不发射子弹

        // 创建子弹
        let bullet = PoolManager.instance.createObjectByName('bullet', this.node.parent);
        // bullet.parent = this.node; // 将子弹添加到当前节点下
        bullet.setPosition(this.node.position)

        // 初始化子弹目标
        let bulletScript = bullet.getComponent('Bullet');

        if (bulletScript) {
            bulletScript.init(nearestEnemy, StorageManager.instance.spreadCount); // 设置子弹的目标
        }


        let ball = PoolManager.instance.createObjectByName('bullet', this.node.parent);
        // bullet.parent = this.node; // 将子弹添加到当前节点下
        ball.setPosition(this.node.position)

        // 初始化子弹目标
        let ballScript = bullet.getComponent(Ball);

        if (ballScript) {
            ballScript.init(nearestEnemy); // 设置子弹的目标
        }
    }

    setCanspread() {
        let skills = JsonManager.instance.getDataByName('skill');
        StorageManager.instance.skills.forEach(id => {

            let effect: Skill = skills[id]
            if (effect) {
                switch (effect.type) {

                    case "spread":
                        this.canSpred = true;

                        break;

                }
            }

        });

    }



    applySkillEffect() {
        this.setCanspread();
        let skills = JsonManager.instance.getDataByName('skill');
        let range = 100;
        let bulletCount = 1;

        let spreadCount = this.canSpred ? 1 : 0;
        let carCount = 1;
        let carCd = 12;
        let ballCount = 1
        let ballstregth = 0;
        let ballSpeed = 0
        StorageManager.instance.se
        // StorageManager.instance.skills.forEach(id => {
        //     let effect: Skill = skills[id]

        //     switch (effect.type) {
        //         case 'carCount':
        //             carCount++
        //         case 'ballStrenth':
        //             ballstregth += (effect.damage * 0.01)
        //         case 'ballCount':
        //             ballCount++
        //         case 'ballSpeed':
        //             ballSpeed += (effect.damage * 0.01)
        //         case 'carCd':
        //             carCd--
        //         case "spreadCount":
        //             spreadCount += 1;
        //             break;
        //         case "bulletCount":
        //             bulletCount += effect.damage;
        //             break;
        //         case "explosion":
        //             StorageManager.instance.canExplode = effect.damage;
        //             break;
        //         case "explosionRadiusMultiplier":
        //             range += effect.damage
        //             break;
        //     }
        // });
        DD.instance.setAttackDAta()
        let minTime = 6
        StorageManager.instance.carCd = carCd >= minTime ? carCd : minTime;
        StorageManager.instance.carCount = carCount;
        StorageManager.instance.ballCount = ballCount;
        StorageManager.instance.ballStrenth = ballstregth;
        StorageManager.instance.spreadCount = spreadCount;
        StorageManager.instance.explosionRadius = range * 0.01;
        StorageManager.instance.playerData.bulletCount = bulletCount;
        if (StorageManager.instance.skills.includes("7")) {
            this.unschedule(this.spawnCar)
            this.schedule(this.spawnCar, StorageManager.instance.carCd);
        } else {
            this.unschedule(this.spawnCar)
        }
        if (StorageManager.instance.skills.includes("11")) {
            this.unschedule(this.spawnBall)
            this.schedule(this.spawnBall, StorageManager.instance.ballCd);
        } else {

            cc.log('解除弹球')
            this.unschedule(this.spawnBall)
        }

    }

    spawnCar() {
        for (let i = 0; i < StorageManager.instance.carCount; i++) {
            let enemy = PoolManager.instance.createObjectByName('car', this.node.parent)
            // 随机设置敌人位置
            const screenWidth = cc.view.getVisibleSize().width - 50;
            const randomX = Math.random() * screenWidth - screenWidth / 2;

            enemy.setPosition(randomX, this.node.y)
        }

    }


    spawnBall() {
        
       this.spawnOnce()
       if(Utils.getRandomNumInRange(0,100)<DD.instance.doubleBallRAte){
        cc.log('双重事发')
        this.spawnOnce()
       }

    }

    spawnOnce(){
        for (let i = 0; i < StorageManager.instance.ballCount; i++) {
            let enemy = PoolManager.instance.createObjectByName('ball', MainManager.instance.genObjContaier)
            // 随机设置敌人位置
            const screenWidth = cc.view.getVisibleSize().width - 50;
            const randomX = Math.random() * screenWidth - screenWidth / 2;
            enemy.setPosition(randomX, this.node.y)
            enemy.name = 'ball'
            enemy.getComponent(Ball).init()
        }
    }

    findNearestEnemy() {
        let nearestEnemy = null;
        let minDistance = Infinity;

        MainManager.instance.enemies.forEach(enemy => {
            if (enemy && enemy.node) {
                let distance = this.node.position.sub(enemy.node.position).mag();
                if (distance < minDistance) {
                    minDistance = distance;
                    nearestEnemy = enemy;
                }
            }

        });

        return nearestEnemy;
    }

    // update (dt) {}
}
